package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.*;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MyCenterService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private SettingsService settingsService;
    @Autowired
    private TanHuaService tanHuaService;
    @Autowired
    private IMService iMService;
    @Autowired
    private BlackListService blackListService;


    @Autowired
    private RecommendUserService recommendUserService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;


    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.get().getId();
        }
        //查询用户信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "women");
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }


    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setAge(Integer.valueOf(userInfoVo.getAge()));
        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(), "K", ""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");
        return this.userInfoService.updateUserInfoByUserId(userInfo);
    }

    //修改个人信息
    public Boolean updateUserInfo(Map<String, Object> map) {

        if (map.size() == 0) {
            return false;
        }

        User user = UserThreadLocal.get();
        //获取修改后的用户信息
        String nickname = Convert.toStr(map.get("nickname"));
        String birthday = Convert.toStr(map.get("birthday"));
        SexEnum gender = StringUtils.equalsIgnoreCase(Convert.toStr(map.get("gender")), "man") ? SexEnum.MAN : SexEnum.WOMAN;
        String city = Convert.toStr(map.get("city"));
        String education = Convert.toStr(map.get("education"));
        String income = Convert.toStr(map.get("income"));
        String profession = Convert.toStr(map.get("profession")); //行业
        String marriage = Convert.toInt(map.get("marriage")) == 1 ? "已婚" : "未婚";

        UserInfo userInfo = UserInfo.builder().userId(user.getId()).nickName(nickname).birthday(birthday).sex(gender).city(city)
                .edu(education).income(income).industry(profession).marriage(marriage)
                .build();


        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        int count = userInfoMapper.update(userInfo, queryWrapper);

        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }


    //修改头像
    public Boolean updateUserLogo(MultipartFile picFile) {
        if (ObjectUtil.isEmpty(picFile)) {
            return false;
        }

        PicUploadResult uploadResult = picUploadService.upload(picFile);
        if (uploadResult.getStatus().equals("error")) {
            return false;
        }

        String logoUrl = uploadResult.getName();
        System.out.println(logoUrl);
        User user = UserThreadLocal.get();

        UserInfo userInfo = UserInfo.builder().logo(logoUrl).id(user.getId()).build();
        int count = userInfoMapper.updateById(userInfo);

        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    //修改陌生人问题
    public Boolean updateUserQuestions(String content) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        //查询之前是否设置有陌生人问题（问题的唯一性）
        Question question = questionService.queryQuestion(user.getId());
        if (ObjectUtil.isEmpty(question)){
            return questionService.saveUserQuestions(userId,content);
        }else{

            return questionService.updateUserQuestions(userId, content);
        }

    }

    public SettingsVo querySettings() {
        SettingsVo settingsVo = new SettingsVo();

        User user = UserThreadLocal.get();

        Settings settings = settingsService.querySettings(user.getId());

        if (ObjectUtil.isEmpty(settings)) {
            return settingsVo;
        }

        settingsVo.setId(Convert.toInt(settings.getUserId()));
        settingsVo.setPhone(user.getMobile());
        settingsVo.setStrangerQuestion(tanHuaService.queryQuestion(user.getId()));
        settingsVo.setGonggaoNotification(settings.getGonggaoNotification() == 1 ? true : false);
        settingsVo.setLikeNotification(settings.getLikeNotification() == 1 ? true : false);
        settingsVo.setPinglunNotification(settings.getPinglunNotification() == 1 ? true : false);

        return settingsVo;

    }

    public Boolean saveSettings(Map<String, Boolean> param) {

        User user = UserThreadLocal.get();
        Integer likeNotification = param.get("likeNotification") ? 1 : 0;
        Integer pinglunNotification = param.get("pinglunNotification") ? 1 : 0;
        Integer gonggaoNotification = param.get("gonggaoNotification") ? 1 : 0;

        Settings newSettings = Settings.builder().userId(user.getId()).likeNotification(likeNotification)
                .gonggaoNotification(gonggaoNotification).pinglunNotification(pinglunNotification)
                .build();

        Settings oldSettings = settingsService.querySettings(user.getId());
        if (ObjectUtil.isEmpty(oldSettings)) {
            //没有数据时，添加
            return settingsService.saveSettings(newSettings);
        } else {
            //修改
            newSettings.setId(Convert.toLong(oldSettings.getId()));
            return settingsService.updateSettings(newSettings);
        }

    }

    public CountsVo queryCounts() {
        User user = UserThreadLocal.get();
        CountsVo countsVo = new CountsVo();

        countsVo.setEachLoveCount(this.userLikeApi.queryMutualLikeCount(user.getId()));
        countsVo.setFanCount(this.userLikeApi.queryFanCount(user.getId()));
        countsVo.setLoveCount(this.userLikeApi.queryLikeCount(user.getId()));

        return countsVo;
    }

    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickname) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get().getId();

        List<Object> userIdList = null;

        //1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch(type){
            case 1:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryMutualLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 2:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "likeUserId");
                break;
            }
            case 3:{
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 4:{
                PageInfo<Visitors> pageInfo = this.visitorsApi.topVisitor(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "visitorUserId");
                break;
            }
            default:
                return pageResult;
        }

        if(CollUtil.isEmpty(userIdList)){
            return pageResult;
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);
        if(StrUtil.isNotEmpty(nickname)){
            queryWrapper.like("nick_name", nickname);
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<UserLikeListVo> userLikeListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserLikeListVo userLikeListVo = new UserLikeListVo();
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            userLikeListVo.setNickname(userInfo.getNickName());
            //是否喜欢  userLikeApi中的isLike开放出来
            userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(userId, userInfo.getUserId()));


            Double score = this.recommendUserService.queryScore(userId, userInfo.getUserId());
            userLikeListVo.setMatchRate(Convert.toInt(score));

            userLikeListVos.add(userLikeListVo);
        }

        pageResult.setItems(userLikeListVos);

        return pageResult;
    }

    /**
     * 取消喜欢
     *
     * @param userId
     */
    public void disLike(Long userId) {
        //判断当前用户与此用户是否相互喜欢
        User user = UserThreadLocal.get();
        Boolean mutualLike = this.userLikeApi.isMutualLike(user.getId(), userId);

        //取消喜欢
        this.userLikeApi.notLikeUser(user.getId(), userId);

        if(mutualLike){
            //取消好友关系，解除在环信平台的好友关系
            this.iMService.removeUser(userId);
        }
    }



    /**
     * 喜欢
     *
     * @param userId
     */
    public void likeFan(Long userId) {
        //喜欢用户，如果用户是相互喜欢的话就会成为好友
        this.tanHuaService.likeUser(userId);
    }

    /**
     * @Description:  查询黑名单列表
     * @Param:  [page, pageSize]
     */
    public PageResult queryBlackList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        IPage<BlackList> blackListIPage = blackListService.queryBlackList(user.getId(), page, pageSize);

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setPages(Convert.toInt(blackListIPage.getPages()));
        pageResult.setCounts(Convert.toInt(blackListIPage.getTotal()));

        List<BlackList> records = blackListIPage.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        List<Object> userIdList = CollUtil.getFieldValues(records, "blackUserId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userIdList);

        List<BlackListVo> blackListVoList=new ArrayList<>();
        BlackListVo blackListVo;
        for (UserInfo userInfo : userInfos) {
            blackListVo=new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setNickname(userInfo.getNickName());

            blackListVoList.add(blackListVo);
        }

        pageResult.setItems(blackListVoList);

        return pageResult;
    }

    public Boolean removeBlackListByUserId(Long blackListUserId) {
        User user = UserThreadLocal.get();
        return blackListService.removeBlackListByUserId(user.getId(),blackListUserId);
    }
}